<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebRTC Demo Client</title>
    <script src="../../../Research/bg-web-rtcstudy/Web/js/peerjs.min.js"></script>
    <script type="application/javascript">
        /**
         * 定义全局变量
         */
        let local_peer = null;    // 本地peer对象
        let local_peer_id = "";
        let remote_peer_id = "";
        let last_local_peer_id = "";
        let remote_peer_conn = null;
        let stun_address = "";

        /**
         *
         */
        function onClickBtnInitialize() {
            stun_address = document.getElementById("stun_address").value;
            local_peer_id = document.getElementById("myid").value;
            remote_peer_id = document.getElementById("remoteid").value;

            let peer_config = {config: {'iceServers': [{ urls: [stun_address] }]}};

            // Create own peer object with connection to shared PeerJS server
            local_peer = new peerjs.Peer(local_peer_id, peer_config);

            local_peer.on('open', function (id) {
                // Workaround for peer.reconnect deleting previous id
                if (local_peer.id === null) {
                    console.log('Received null id from peer open');
                    local_peer.id = last_local_peer_id;
                } else {
                    last_local_peer_id = local_peer.id;
                }

                console.log('ID: ' + local_peer.id);
            });
            local_peer.on('connection', function (c) {
                // Disallow incoming connections
                c.on('open', function() {
                    c.send("Sender does not accept incoming connections");
                    setTimeout(function() { c.close(); }, 500);
                });
            });

            local_peer.on('disconnected', function () {
                console.log('Connection lost. Please reconnect');

                // Workaround for peer.reconnect deleting previous id
                local_peer.id = last_local_peer_id;
                local_peer._lastServerId = last_local_peer_id;
                local_peer.reconnect();
            });
            local_peer.on('close', function() {
                remote_peer_conn = null;
                console.log('Connection destroyed. Please refresh');
            });
            local_peer.on('error', function (err) {
                console.log(err);
                alert('' + err);
            });
        }

        /**
         *
         */
        function join() {
            // Close old connection
            if (remote_peer_conn) {
                remote_peer_conn.close();
            }

            // Create connection to destination peer specified in the input field
            remote_peer_conn = local_peer.connect(remote_peer_id, {
                reliable: true
            });

            remote_peer_conn.on('open', function () {
                console.log("Connected to: " + remote_peer_conn.peer);

                // Check URL params for comamnds that should be sent immediately
                let command = getUrlParam("command");
                if (command)
                    remote_peer_conn.send(command);
            });

            // Handle incoming data (messages only since this is the signal sender)
            remote_peer_conn.on('data', function (data) {
                console.log(" Peer : " + data);
            });

            remote_peer_conn.on('close', function () {
                console.log("Connection closed");
            });
        }

        /**
         *
         */
        function getUrlParam(name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            let regexS = "[\\?&]" + name + "=([^&#]*)";
            let regex = new RegExp(regexS);
            let results = regex.exec(window.location.href);
            if (results == null)
                return null;
            else
                return results[1];
        }

        /**
         *
         */
        function onClickBtnSendMessage() {
            let message = document.getElementById("message_box").value;
            if (message === "") {
                return 0;
            } else {
                updateMessageRecord(local_peer_id, message);
            }

        }

        /**
         *
         */
        function updateMessageRecord(peer_id, data) {
            let message_record = document.getElementById("message_record");
            let message_record_msg = message_record.innerText;
            if (message_record_msg === "") {
                message_record_msg += remote_peer_id + "\r\n" + data;
            } else {
                message_record_msg += "\r\n\r\n" + remote_peer_id + "\r\n" + data;
            }

            message_record.innerText = message_record_msg;
        }
    </script>
</head>
<body>
    <span>Click "Initialize" button to initialize peer.</span><input type="button" id="initialize" value="Initialize" onclick="onClickBtnInitialize()" /><br />
    <hr>
    <span>STUN Address:</span><label for="stun_address"></label><input type="text" id="stun_address" value="stun:stun.voipstunt.com" /><br />
    <span>TURN Address:</span><label for="turn_address"></label><input type="text" id="turn_address" value="" /><br />
    <span>My ID : </span><label for="myid"></label><input type="text" id="myid" value="100002" /><br />
    <span>Remote ID : </span><label for="remoteid"></label><input type="text" id="remoteid" value="100001" /><br />
    <input type="button" id="connect" value="Connect" onclick="join()">
    <hr>
    <span>Message record</span><br />
    <textarea id="message_record" class="message_record" rows="20" cols="80"></textarea><br />
    <span>Message : </span><input type="text" id="message_box" value="" /><input type="button" value="Send"  onclick="onClickBtnSendMessage()" />
</body>
</html>